package com.android.datn.adapter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.android.datn.R;
import com.android.datn.activities.ADetailMusic;
import com.android.datn.activities.ASongOfFavorite;
import com.android.datn.adapter.TracksAdapter.VoteAsync;
import com.android.datn.daos.TrackDAO;
import com.android.datn.helper.DBBinding;
import com.android.datn.helper.JSonCustomException;
import com.android.datn.objects.Track;
import com.android.datn.repositories.MusicRepository;
import com.android.datn.utils.CommonUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ParserError")
public abstract class TrackListAdapter extends ArrayAdapter<Track> {
	private int resourceID;
	protected Context ctx;
	private ProgressDialog mProgressDialog;
	private TrackDAO mTrackDAO;
	private MusicRepository mMusicRespository;
	private boolean mIsVote = false;

	public TrackListAdapter(Context context, int resourceID, List<Track> objects) {
		super(context, resourceID, objects);
		this.resourceID = resourceID;
		this.ctx = context;
		mProgressDialog = new ProgressDialog(this.ctx);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setMessage("Please wait... Uploading.");
		mProgressDialog.setCancelable(false);
		mMusicRespository = new MusicRepository();
		mTrackDAO = TrackDAO.getInstance();
	}

	@SuppressWarnings("deprecation")
	@SuppressLint({ "ParserError", "ParserError", "NewApi", "ParserError",
			"ParserError" })
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Track track = getItem(position);
		View row = convertView;
		final ViewHolder holder;
		if (row == null) {
			LayoutInflater inflater;
			inflater = (LayoutInflater) getContext().getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(this.resourceID, null);
			holder = new ViewHolder();
			holder.positionImage = position;
			holder.imageVote = (ImageView) row.findViewById(R.id.img_vote);
			holder.positionImage = position;
			row.setTag(holder);
		} else {
			holder = (ViewHolder) row.getTag();
			holder.positionImage = position;
		}
		if (track.isFavorite()) {
			holder.imageVote.setVisibility(View.GONE);
		} else {
			holder.imageVote.setVisibility(View.VISIBLE);
			holder.imageVote.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (mTrackDAO.getSizeByTitleAndArtist(track,
							DBBinding.DB_VOTE) > 0) {
						mIsVote = true;
					} else {
						mIsVote = false;
					}
					List<NameValuePair> list = new ArrayList<NameValuePair>();
					NameValuePair value = new org.apache.http.message.BasicNameValuePair(
							"id", String.valueOf(track.getId()));
					list.add(value);
					value = new org.apache.http.message.BasicNameValuePair(
							"post", "update");
					list.add(value);
					VoteAsync ws = new VoteAsync();
					ws.execute(
							"http://www.mrmai.info/products/musicrank/apis/1.0/do_vote",
							list, holder.positionImage);
				}
			});
		}
		TextView txtTitle = (TextView) row.findViewById(R.id.txt_title);
		TextView txtArtist = (TextView) row.findViewById(R.id.txt_artist);
		TextView txtNumListen = (TextView) row
				.findViewById(R.id.txt_num_listen);
		TextView txtNumVote = (TextView) row.findViewById(R.id.txt_num_vote);
		TextView txtNumber = (TextView) row.findViewById(R.id.txt_num);
		txtTitle.setText(track.getTitle().trim());
		if (track.getArtist().trim().toUpperCase().equals("NULL")) {
			txtArtist.setText("Đang cập nhật");
		} else {
			txtArtist.setText(track.getArtist().trim());
		}
		RelativeLayout layoutType = (RelativeLayout) row
				.findViewById(R.id.layout_type);
		if (track.getType() == 1) {
			txtNumListen.setText(track.getListen().trim());
			txtNumVote.setText(track.getVote().trim());
			txtNumVote.setVisibility(View.VISIBLE);
			layoutType.setVisibility(View.VISIBLE);
		} else {
			if (track.isFavorite()) {
				txtNumListen.setText(track.getListen().trim());
				txtNumVote.setVisibility(View.GONE);
				layoutType.setVisibility(View.VISIBLE);
			} else {
				layoutType.setVisibility(View.GONE);
			}
		}
		txtNumber.setText(String.valueOf(position + 1));
		ImageView imgListening = (ImageView) row
				.findViewById(R.id.img_listening);
		if (track.isListening()) {
			imgListening.setVisibility(View.VISIBLE);
			imgListening.setBackgroundDrawable(ctx.getResources().getDrawable(
					R.drawable.ic_listen_1));
		} else {
			if (track.getType() == 1) {
				imgListening.setVisibility(View.INVISIBLE);
			} else {
				imgListening.setVisibility(View.VISIBLE);
				imgListening.setBackgroundDrawable(ctx.getResources()
						.getDrawable(R.drawable.ic_memory));
			}
		}
		/*
		 * row.setOnClickListener(new View.OnClickListener() {
		 * 
		 * @Override public void onClick(View v) { // TODO Auto-generated method
		 * stub Toast.makeText(ctx, String.valueOf(holder.positionImage),
		 * Toast.LENGTH_SHORT).show(); } });
		 */
		// row.setAnimation(inFromRightAnimation());

		return row;
	}

	private Animation inFromRightAnimation() {

		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(500);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	private class ViewHolder {
		public ImageView imageVote;
		public int positionImage;
	}

	public class VoteAsync extends AsyncTask<Object, Void, Object> {
		private int position;

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			JSONObject json = null;
			try {
				if (!mIsVote) {
					position = (Integer) params[2];
					json = CommonUtil.getJSONFromUrlParams((String) params[0],
							(List<NameValuePair>) params[1]);
					mTrackDAO.addTrack(getItem(position), DBBinding.DB_VOTE);
				}
			} catch (JSonCustomException e) {
				return e.getMessage();
			} catch (UnsupportedEncodingException e) {
				return e.getMessage();
			} catch (IOException e) {
				return e.getMessage();
			}
			return json;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mProgressDialog.show();
		}

		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub

			if (result instanceof JSONObject || result == null) {
				if (!mIsVote) {
					int count = Integer.parseInt(getItem(position).getVote()) + 1;
					getItem(position).setVote(String.valueOf(count));
					notifyDataSetChanged();
					processVote(position);
				} else {
					Toast.makeText(ctx, "You voted", Toast.LENGTH_SHORT).show();
				}
			} else {
				Activity activity = (Activity) ctx;
				if (activity instanceof ASongOfFavorite
						|| activity instanceof ADetailMusic) {
					CommonUtil.dialogNotify(ctx, (((String) result)),
							"Music Online");
				} else {
					CommonUtil.dialogNotify(((Activity) ctx).getParent()
							.getParent(), (((String) result)), "Music Online");
				}
			}
			mProgressDialog.dismiss();
		}
	}

	public abstract void processVote(int position);
}
